import { useState, forwardRef, useImperativeHandle } from 'react'

import {
  Modal,
  Form,
  Input,
  Radio,
  DatePicker,
  InputNumber,
  message
} from 'antd'

import dayjs from 'dayjs'

import { addUserData, updateUserData } from '@/api/home'

const DataProcess = forwardRef((props: General.componentProp, ref) => {
  const [form] = Form.useForm()

  const [showModal, setShowModal] = useState(false) // 控制模态框的显示与隐藏
  const [isUpdate, setIsUpdate] = useState(false) // 判断是更新还是新增
  const [submitId, setSubmitId] = useState('') // 提交的ID

  const [messageApi, contextHolder] = message.useMessage()

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    openModal
  }))
  // 打开的回调
  const openModal = (isBoolean: boolean, data: UserData.User) => {
    if (isBoolean) {
      form.setFieldsValue({
        name: data.name,
        age: data.age,
        sex: data.sex,
        addr: data.addr,
        birth: dayjs(data.birth)
      })

      setSubmitId(data.id) // 设置提交的ID

      setIsUpdate(true) // 设置为更新状态
    }
    setShowModal(true)
  }

  // 确认按钮的处理函数
  const handleOk = () => {
    form
      .validateFields()
      .then(values => {
        // 提交表单数据
        if (isUpdate) {
          update(values)
        } else {
          save(values)
        }
      })
      .catch(info => {
        console.log('Validate Failed:', info)
      })
  }

  // 保存
  const save = async (values: UserData.User) => {
    const { data } = await addUserData(values)

    messageApi.success(data.message, 1, () => {
      props.handleSuccess()
      handleClose()
    })
  }

  // 更新
  const update = async (values: UserData.User) => {
    const { data } = await updateUserData({ ...values, id: submitId })
    messageApi.success(data.message, 1, () => {
      props.handleSuccess()
      handleClose()
    })
  }

  // 取消
  const handleCancel = () => {
    handleClose()
  }

  const handleClose = () => {
    setShowModal(false)
    form.resetFields() // 重置表单
  }

  return (
    <>
      {contextHolder}
      <Modal
        title={isUpdate ? '更新用户' : '新增用户'}
        open={showModal}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div>
          <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
            <Form.Item
              label="用户名"
              name="name"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item label="年龄" name="age">
              <InputNumber min={1} controls={false} placeholder="请输入年龄" />
            </Form.Item>
            <Form.Item label="性别" name="sex">
              <Radio.Group>
                <Radio value={1}>男</Radio>
                <Radio value={0}>女</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="出生日期" name="birth">
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="地址" name="addr">
              <Input placeholder="请填写地址" />
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </>
  )
})

export default DataProcess
